import { ElMessage, ElNotification } from 'element-plus'
import { hash } from 'ohash'
import { App_Id } from '~~/config'
// import qs from 'qs'

const apiUrl = import.meta.env.VITE_API_URL

export const fetchConfig = {
  baseURL: `${apiUrl}`,
  headers: {
    appId: App_Id,
    token: getToken(),
  },
}

// 请求体封装
function useGetFetchOptions(options: any = {}) {
  options.baseURL = options.baseURL ?? fetchConfig.baseURL
  options.headers = options.headers ?? fetchConfig.headers

  return options
}

// http请求封装
export async function useHttp(key: string, url: string, options: any = {}) {
  options = useGetFetchOptions(options)

  options.key = key ?? hash(JSON.stringify(options) + url)

  const error = ref(null)

  return await $fetch(url, options)
    .then((res: any) => {
      const { code, data, message } = res
      const errMsg = message || '系统异常，请稍候再试'

      if (typeof code !== 'undefined' && code !== 0) {
        ElNotification.error(errMsg)
        error.value = errMsg
      }

      return { data, error }
    })
    .catch((err) => {
      console.log('error.data: ', err.data)
      const msg = err?.data?.message

      if (process.client) {
        ElMessage.error(msg || '服务端错误')
      }

      error.value = msg

      return { error }
    })
}
type SearchParams = typeof URLSearchParams
type UseFetchOptions = {
  key?: string
  method?: string
  query?: SearchParams
  params?: Omit<SearchParams, 'prototype'>
  body?: RequestInit['body'] | Record<string, any>
  headers?: { key: string; value: string }[]
  baseURL?: string
  server?: boolean
  lazy?: boolean
  immediate?: boolean
  pick?: string[]
}

// GET请求
export function useHttpGet(key: string, url: string, options: UseFetchOptions = {}) {
  options.method = 'GET'

  return useHttp(key, url, options)
}

// POST请求
export function useHttpPost(key: string, url: string, options: UseFetchOptions = {}) {
  options.method = 'POST'

  return useHttp(key, url, options)
}

// PATCH请求
export function useHttpPatch(key: string, url: string, options: any = {}) {
  delete options.body.id
  options.method = 'PATCH'

  return useHttp(key, url, options)
}
